const Router = require('koa-router')
const fs = require('fs')
const path = require('path')

const router = new Router({ prefix: '/upload' })

router.post('/img', async (ctx, next) => {
  const fileName = ctx.request.files.file.name
  const file = ctx.request.files.file
  // 创建可读流
  const render = fs.createReadStream(file.path)
  let filePath = path.join(
    __dirname,
    '../../html/images',
    fileName + '.' + file.name.split('.')
  )
  const fileDir = path.join(__dirname, '../../html/images')
  if (!fs.existsSync(fileDir)) {
    fs.mkdirSync(fileDir, err => {
      console.log(err)
      console.log('创建失败')
    })
  }
  console.log(11)
  // 创建写入流
  const upStream = fs.createWriteStream(filePath)
  render.pipe(upStream)
  ctx.body = {
    code: 200,
    message: '上传成功',
    url: '/di-img/' + fileName
  }
})

module.exports = router
